package service

import (
	"context"
	"database/sql"
	"encoding/json"
	"fx_swift_schedule/api"
	"fx_swift_schedule/pkg/code"
	"fx_swift_schedule/pkg/global"
	"fx_swift_schedule/pkg/internalerrors"
	"fx_swift_schedule/pkg/logger"
	"github.com/gogf/gf/v2/frame/g"
)

type IAccessTokenSrv interface {
	GetAccessToken(ctx context.Context, merOrderNo string, authorizeCode string) (string, error)
}

type accessToken struct {
}

func NewAccessToken() IAccessTokenSrv {
	return &accessToken{}
}

func (a accessToken) GetAccessToken(ctx context.Context, merOrderNo string, authorizeCode string) (string, error) {
	var (
		//tradeCode string
		err      error
		result   sql.Result
		rowsNums int64
		resp     []byte
	)

	req := &api.TokenReq{}
	req.AuthorizeCode = authorizeCode
	body, _ := json.Marshal(req)

	resp, err = OperatorParamToPost("tp9002", "", body)
	if err != nil {
		return "", err
	}

	//返回结果集解析
	resObj := &api.TokenRes{}
	err = json.Unmarshal(resp, &resObj)
	if err != nil {
		logger.SugarLogger.Errorf("json转换:%w", err)
		return "", err
	}

	if result, err = global.GFDB.Ctx(ctx).Model("ifcgate_merchant_va_info").
		Data(g.Map{"access_token": resObj.TokenBody.AccessToken}).
		Where("mer_order_no=?", merOrderNo).Update(); err != nil {
		logger.SugarLogger.Error(err)
		return "", internalerrors.New(code.ErrUnknown, "更新异常")
	}
	rowsNums, err = result.RowsAffected()
	if err != nil || rowsNums == 0 {
		logger.SugarLogger.Error(err)
		return "", internalerrors.New(code.ErrUnknown, "更新异常")
	}
	return resObj.TokenBody.AccessToken, err
}
